package com.jh.paymentchannel.service;

import cn.jh.common.utils.CommonConstants;
import com.alibaba.fastjson.TypeReference;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.MiLianQuickRegister;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.milian.bean.*;
import com.jh.paymentchannel.util.milian.utils.HttpHelper;
import com.jh.paymentchannel.util.milian.utils.ParamsUtil;
import com.jh.paymentchannel.util.milian.utils.SignUtil;
import com.jh.paymentchannel.util.milian.utils.XmlUtil;
import net.sf.json.JSONObject;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@EnableAutoConfiguration
public class MilianQuickpageRequest {

	private static final Logger log = LoggerFactory.getLogger(MilianQuickpageRequest.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;
	
	@Value("${payment.ipAddress}")
    private String ipAddress;

	@Value("${mlquick.parent}")
	private String parent;// = "CSRZ0001";

	@Value("${mlquick.key}")
	private String key;// = "F7D5245A8F7577BDDEBFF9798150B066";

    /*进件URL*/
	@Value("${mlquick.RegisterUrl}")
    private String RegisterUrl;// = "http://220.160.118.218:8382/ChannelPay/merchBaseInfo/merchInterface";

	/*交易URL*/
	@Value("${mlquick.MlQuickPayUrl}")
	private String MlQuickPayUrl;// = "http://220.160.118.218:8281/MyLandQuickPay/controller/pay";

	/*代付URL*/
	@Value("${mlquick.MlQuickDFUrl}")
	private String MlQuickDFUrl;// = "http://220.160.118.218:8280/WeChatPay/servlet/DfReq";

	/*绑卡查询*/
	@Value("${mlquick.MlCardInfoQueryURL}")
    private String MLCardInfoQueryURL;// = "http://220.160.118.218:8280/WeChatPay/servlet/CardInfoQuery";

	/*交易结果查询*/
    @Value("${mlquick.MlOrderQueryURL}")
    private String MLOrderQueryURL;// = "http://220.160.118.218:8280/WeChatPay/servlet/Query";

    /*绑卡URL*/
	@Value("${mlquick.bindCardUrl}")
    private String MLBankCardURL;// = "http://220.160.118.218:8281/MyLandQuickPay/controller/pay";

    /*商户余额查询URL*/
	@Value("${mlquick.MlMerchBalanceQueryURL}")
    private String MLMerchBalanceQueryURL;// = "http://220.160.118.218:8280/WeChatPay/servlet/MerchBalanceQuery";

    /*进件接口*/
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/milianQuick/register")
    public @ResponseBody Object register(HttpServletRequest request,
                                         @RequestParam(value = "ordercode") String ordercode,
                                         @RequestParam(value = "handleType", defaultValue = "A", required = false) String handleType
                                         ) throws Exception {
        log.info("米联代扣代还进件 miLianJinJian 包含新增与自动更新============");
        Map resultMap = new HashMap();

        // --- check order
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("米联进件 miLianJinJian 查询订单信息RESULT================" + result);
        JSONObject jsonObject;
        JSONObject orderResultObj;
        try {
            jsonObject = JSONObject.fromObject(result);
            orderResultObj = jsonObject.getJSONObject("result");
        } catch (Exception e1) {
            log.error("查询订单信息出错");
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "没有该订单信息");
            return resultMap;
        }

        String userId = orderResultObj.getString("userid");
        // 代扣卡卡号
        String bankCard = orderResultObj.getString("bankcard");

        String costFee = orderResultObj.getString("costfee");

        // --- check user
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/query/id";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("id", userId );
        restTemplate = new RestTemplate();
        JSONObject userResultObj;
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            jsonObject = JSONObject.fromObject(result);
            userResultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("==========米联进件 miLianJinJian /v1.0/user/query/id查询用户异常===========" + e);
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "查询用户异常");
            return resultMap;
        }

        // 查询绑定的信用卡信息
        restTemplate = new RestTemplate();
        String bankName = null;
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/cardno";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("cardno", bankCard);
        requestEntity.add("type", "0");
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
        JSONObject withdrawBankresultObj = null;
        try {
            jsonObject = JSONObject.fromObject(result);
            withdrawBankresultObj = jsonObject.getJSONObject("result");
            bankName = withdrawBankresultObj.getString("bankName");
        } catch (Exception e) {
            log.error("查询银行卡信息出错");
            resultMap.put("resp_code", "failed");
            resultMap.put("channel_type", "milian_quick");
            resultMap.put("resp_message", "查询银行卡信息有误");
            return resultMap;
        }

        // --- check random shops
        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/query/randomshopid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        String randomShopId;
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            jsonObject = JSONObject.fromObject(result);
            randomShopId = jsonObject.getString("result");
        } catch (Exception e1) {
            log.error(" 米联进件 miLianJinJian 随机获取的 shopId出错！！！！");
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "进件商户失败");
            return resultMap;
        }
        log.info("随机获取的 shopId:" + randomShopId);
        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/shops/query/shopid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("shopid", randomShopId);
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("shop info by shopId RESULT================" + result);
        JSONObject shopInfoResultObj;
        try {
            jsonObject = JSONObject.fromObject(result);
            shopInfoResultObj = jsonObject.getJSONObject("result");
        } catch (Exception e1) {
            log.error(" 米联进件 miLianJinJian 查询商铺信息出错！！！！shopId:" + randomShopId);
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "用户进件失败");
            return resultMap;
        }

        /**获取银行编号*/
        restTemplate=new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/number/name";
        requestEntity  = new LinkedMultiValueMap<String, String>();
        requestEntity.add("bank_name", bankName);
        JSONObject bankCodeResultObj;
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            log.info("RESULT================"+result);
            jsonObject =  JSONObject.fromObject(result);
            bankCodeResultObj  =  jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("获取银行编号出错啦========"+e);
            resultMap.put(CommonConstants.RESP_CODE, "failed");
            resultMap.put(CommonConstants.RESP_MESSAGE, "获取银行编号出错啦");
            return resultMap;
        }

        // 根据银行名称获取银行编码
        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bankcode/getcodebyname";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("name", bankName);
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("米联进件 miLianJinJian 获取银行编码RESULT================" + result);
        try {
            jsonObject = JSONObject.fromObject(result);
        } catch (Exception e) {
            log.error("米联进件 miLianJinJian -- 根据银行名称获取银行编码失败 bankName:" + bankName);
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "根据银行名称获取银行编码失败");
            return resultMap;
        }
        // 银行编号
        String withdrawBankCode = jsonObject.getString("result");

        log.info("米联进件 miLianJinJian 开始检查进件相关数据 -- ");
        String orderExtraFeeStr = orderResultObj.getString("extraFee");
        String rate = orderResultObj.getString("rate");
        String userPhone = userResultObj.getString("phone");
        String withdrawBankUserName = withdrawBankresultObj.getString("userName");
        String withdrawBankCardNo = withdrawBankresultObj.getString("cardNo");
        String withdrawBankIdCard = withdrawBankresultObj.getString("idcard"); // 身份证
        String withdrawBankPhone = withdrawBankresultObj.getString("phone");
        String withdrawBankName = withdrawBankresultObj.getString("bankName");
        String shopName = shopInfoResultObj.getString("name");
        String shopAddress = shopInfoResultObj.getString("shopsaddress");
        //信用卡银行编号
        String bankNumber =  bankCodeResultObj.getString("bankNumber");

        MiLianReginsterBean miLianReginsterBean = new MiLianReginsterBean();
        miLianReginsterBean.setOrderId(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        miLianReginsterBean.setParent(parent);
        miLianReginsterBean.setFutureMinAmount("0"); // 保底 目前没有用
        miLianReginsterBean.setDebitCapAmount("9999"); // 封顶 目前没有用
        BigDecimal countFeeT0 = new BigDecimal(orderExtraFeeStr).multiply(new BigDecimal("100")); // 单位转成分, 元->分
        miLianReginsterBean.setCountFeeT0(countFeeT0.stripTrailingZeros().toPlainString());
        miLianReginsterBean.setDebitRate(rate);
        /*下面三个值为空字符串可以进件成功，已测过*/
        miLianReginsterBean.setBankProvince(" ");
        miLianReginsterBean.setBankCity(" ");
        miLianReginsterBean.setBankChannelNo(" ");

        miLianReginsterBean.setTelNo(withdrawBankPhone);
        miLianReginsterBean.setBankAccountName(withdrawBankUserName);
        miLianReginsterBean.setBankAccountNo(withdrawBankCardNo);
        miLianReginsterBean.setLegalPersonIdcard(withdrawBankIdCard);
        miLianReginsterBean.setPhoneNo(withdrawBankPhone);
        miLianReginsterBean.setSettBankName(withdrawBankName);
        miLianReginsterBean.setBankAbbr(withdrawBankCode);
        miLianReginsterBean.setBankCode(bankNumber);
        miLianReginsterBean.setBankSubName(withdrawBankName);
        miLianReginsterBean.setHandleType(handleType);  // A 新增进件  M 修改进件
        miLianReginsterBean.setMerchName(shopName);
        miLianReginsterBean.setMerchAbb(shopName);
        miLianReginsterBean.setMerchAddress(shopAddress);
        /*随机经营类目*/
        miLianReginsterBean.setCategory(getCategory());

        if(handleType.equals("M")){
			MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userId),bankCard);
			miLianReginsterBean.setChangeType("M03");
			miLianReginsterBean.setMerchId(miLianQuickRegister.getMerchantNo());
		}

        String params = ParamsUtil.getBaseMerchRegisterParams(miLianReginsterBean , key);
        log.info("米联进件 miLianJinJian 开始请求进件参数={} ordercode:" + ordercode ,params);
        String respResult = HttpHelper.doHttp(RegisterUrl, HttpHelper.POST, "UTF-8", params, "60000");

        MilianBaseResMessage<MiLianMerchan> res = com.alibaba.fastjson.JSONObject.parseObject(respResult, new TypeReference<MilianBaseResMessage<MiLianMerchan>>() {
        });

        log.info("米联进件 miLianJinJian 请求入驻接口响应内容：" + res.getRespMsg());
        if ("0000".equals(res.getRespCode())) {
            log.info("米联进件 miLianJinJian 进件成功后处理开始 ordercode:" + ordercode);
            MiLianQuickRegister miLianQuickRegister = new MiLianQuickRegister();
            miLianQuickRegister.setUserId(Long.parseLong(userId));
            miLianQuickRegister.setBankCard(withdrawBankCardNo);
            miLianQuickRegister.setDebitRate(rate);
            miLianQuickRegister.setName(withdrawBankName);
            miLianQuickRegister.setMerchantNo(res.getData().getMerchantNo());
            miLianQuickRegister.setMerchantKey(res.getData().getMerchantKey());
            miLianQuickRegister.setIdNo(withdrawBankIdCard);
            miLianQuickRegister.setCountFee(costFee);
			MiLianQuickRegister resultMLQuickRegister = null;
			/*判断新进件还是修改进件*/
            if(handleType.equals("M")){
				topupPayChannelBusiness.deleteMiLianRegisterByUIdAndBankId(Long.valueOf(userId),bankCard);
				miLianQuickRegister.setState("Y");
			}
			miLianQuickRegister.setState("N");
			resultMLQuickRegister = topupPayChannelBusiness.createMiLianQuickRegister(miLianQuickRegister);
            log.info("米联进件 miLianJinJian 保存数据库成功, t_ml_register ordercode:" + ordercode + " mlDataId:" + resultMLQuickRegister.getId());
            log.info("米联进件 miLianJinJian --------OK----------");
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            resultMap.put(CommonConstants.RESP_MESSAGE, "进件成功");
            resultMap.put(CommonConstants.RESULT, resultMLQuickRegister);
            return resultMap;
        }else {
            log.info("米联进件 miLianJinJian 进件失败====== ordercode:" + ordercode + " RespCode:" + res.getRespCode() + " msg:" + res.getRespMsg());
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, res.getRespMsg());
            return resultMap;
        }

    }

	// 支付接口
	public Object mlQuickPay(String ordercode,String securityCode,String expiredTime,MiLianQuickRegister miLianQuickRegister){
		log.info("开始进入支付接口==================parent:" + parent);
		MiLianQuickPayBean miLianQuickPayBean = new MiLianQuickPayBean();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "milian_quick");
			maps.put("resp_message", "没有该订单信息");
			return maps;
		}
		String userid = resultObj.getString("userid");
		// 代扣卡卡号
		String bankCard = resultObj.getString("bankcard");

		Double amount = Double.valueOf(resultObj.getString("amount"));
		DecimalFormat df = new DecimalFormat("#.00");
		//组合订单号
		String newMiLianOrderId = ordercode.substring(0,10) + resultObj.getString("id");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "milian_quick");
			maps.put("resp_message", "查询银行卡信息有误");
			return maps;
		}
		String mobile = resultObj.getString("phone"); // 预留信用卡手机号码
		String idcard = resultObj.getString("idcard");// 身份证号
		String userName = resultObj.getString("userName");// 用户姓名

		miLianQuickPayBean.setOrder_id(newMiLianOrderId);
		miLianQuickPayBean.setUser_id(miLianQuickRegister.getMerchantNo());
		miLianQuickPayBean.setOrder_amt(df.format(amount));
		miLianQuickPayBean.setUser_type("02");
		miLianQuickPayBean.setSign_type("03");
		miLianQuickPayBean.setBus_code("5029");
		miLianQuickPayBean.setPay_type("13");
		miLianQuickPayBean.setAdd1(bankCard);
		miLianQuickPayBean.setAdd2(userName);
		miLianQuickPayBean.setAdd3("02");
		miLianQuickPayBean.setAdd4(idcard);
		miLianQuickPayBean.setPhone_no(mobile);
		miLianQuickPayBean.setValid(expiredTime);
		miLianQuickPayBean.setCvn2(securityCode);
		/*异步回调地址*/
		miLianQuickPayBean.setBg_url("/v1.0/paymentchannel/topup/milianQuick/paynotify_call");

		String params = ParamsUtil.getQuickPayYKParams(miLianQuickPayBean ,miLianQuickRegister);
		log.info("米联交易参数信息params={} ordercode:" + ordercode + " newOderId:" + newMiLianOrderId,params);
		String respResult = HttpHelper.doHttp(MlQuickPayUrl, HttpHelper.POST, "UTF-8", params, "60000");
		RequestMsg RM = new RequestMsg();
		XmlUtil xmlUtil = new XmlUtil();
		try {
			xmlUtil.XmlToBean(RM, respResult);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		log.info("米联交易mlQuickPay返回: " + RM.getRESP_CODE() + " || " + RM.getRESP_DESCR());
		if (RM.getRESP_CODE().equals("0000")) {
			SignUtil signUtil = new SignUtil();
			/*暂注释米联验签问题*/
//			Boolean checkResult = signUtil.checkSIGN(RM,miLianQuickRegister);
			Boolean checkResult = true;
			if (checkResult) {
				maps.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				maps.put("channel_type", "milian_quick");
				maps.put(CommonConstants.RESP_MESSAGE, "支付成功啦");
			} else {
				log.info("请求支付接口失败===================" + RM);
				maps.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				maps.put("channel_type", "milian_quick");
				maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
			}
		}else{
			maps.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
		}

		return maps;
	}

	// 单笔代付接口
	public Object mlQuickDF(String ordercode ,MiLianQuickRegister miLianQuickRegister){
		log.info("开始进入米联单笔代付接口======");
		MiLianQuickDFBean miLianQuickDFBean = new MiLianQuickDFBean();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "milian_quick");
			maps.put("resp_message", "没有该订单信息");
			return maps;
		}
		String userid = resultObj.getString("userid");
		// 代付卡卡号
		String bankCard = resultObj.getString("bankcard");

		Double realAmount = Double.valueOf(resultObj.getString("realAmount"));
		DecimalFormat df = new DecimalFormat("#.00");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "milian_quick");
			maps.put("resp_message", "查询银行卡信息有误");
			return maps;
		}

		// 信用卡银行名称
		String bankNameX = resultObj.getString("bankName");
		String userName = resultObj.getString("userName");// 用户姓名

		//信用卡银行编号
		String bankNumber=null;

		/**获取银行编号*/
		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/number/name";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("bank_name", bankNameX);
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("RESULT================"+result);
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
			bankNumber =  resultObj.getString("bankNumber");
		} catch (Exception e) {
			log.error("获取银行编号出错啦========"+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "获取银行编号出错啦");
			return maps;
		}

		//组合订单号
		String newMiLianOrderId = ordercode.substring(0,10) + resultObj.getString("id");
		miLianQuickDFBean.setOrder_id(newMiLianOrderId);
		miLianQuickDFBean.setOrder_amt(df.format(realAmount));
		miLianQuickDFBean.setUser_type("02");
		miLianQuickDFBean.setSign_type("03");
		miLianQuickDFBean.setBus_code("1006");
		miLianQuickDFBean.setBank_code(bankNumber);
		miLianQuickDFBean.setAccount_no(bankCard);
		miLianQuickDFBean.setBank_name(bankNameX);
		miLianQuickDFBean.setAccount_name(userName);
		miLianQuickDFBean.setPay_type("13");
		miLianQuickDFBean.setCct("CNY");
		miLianQuickDFBean.setUser_id(miLianQuickRegister.getMerchantNo());

		String params = ParamsUtil.getPayByOtherParams(miLianQuickDFBean ,miLianQuickRegister);
		log.info("米联交易参数信息params={} ordercode:" + ordercode + " newOderId:" + newMiLianOrderId,params);
		String respResult = HttpHelper.doHttp(MlQuickDFUrl, HttpHelper.POST, "UTF-8", params, "60000");
		log.info("米联代付返回的信息respResult={}",respResult);
		RequestMsg RM = new RequestMsg();
		XmlUtil xmlUtil = new XmlUtil();
		try {
			xmlUtil.XmlToBean(RM, respResult);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		if (RM.getRESP_CODE().equals("0000") || RM.getRESP_CODE().equals("0100") || RM.getRESP_CODE().equals("00")) {
			SignUtil signUtil = new SignUtil();
			/*暂注释米联验签问题*/
//			Boolean checkResult = signUtil.checkSIGN(RM,miLianQuickRegister);
			Boolean checkResult = true;
			if (checkResult) {
				restTemplate = new RestTemplate();

				uri = util.getServiceUrl("transactionclear", "error url request!");
				url = uri.toString() + "/v1.0/transactionclear/payment/update";

				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("status", "1");
				requestEntity.add("order_code", ordercode);
				result = restTemplate.postForObject(url, requestEntity, String.class);

				try {
					jsonObject = JSONObject.fromObject(result);
					String resp_code = jsonObject.getString(CommonConstants.RESP_CODE);
					if(resp_code.equals(CommonConstants.SUCCESS)){
						log.info("米联异步通知 -- 订单状态修改成功====" + result);

						log.info("订单状态修改成功===================");
						log.info("订单已代付!");
						maps.put(CommonConstants.RESP_CODE, "success");
						maps.put("channel_type", "milian_quick");
						maps.put(CommonConstants.RESP_MESSAGE, "支付成功啦");
					}else{
						log.info("米联异步回调成功 -- 订单状态修改失败====" + result);
					}
				} catch (Exception e1) {
					log.error("米联异步通知 pay_notify_call -- 查询订单信息出错====" + e1.getMessage());
				}

			} else {
				log.info("请求支付接口失败===================" + RM);
				maps.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				maps.put("channel_type", "milian_quick");
				maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
			}
		}
		return maps;
	}

	//交易结果查询
	//只针对代扣代付的查询
	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/milianQuick/ordercodequery")
	public @ResponseBody Object mlOrderCodeQuery(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode, @RequestParam(value = "transType") String transType

	) throws Exception {
		log.info("开始进入米联交易结果查询接口======");
		MilianOrderQueryBean milianOrderQueryBean = new MilianOrderQueryBean();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "milian_quick");
			maps.put("resp_message", "没有该订单信息");
			return maps;
		}
		String userid = resultObj.getString("userid");

		MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userid));

		//组合订单号
		String miLianOrgOrderId = ordercode.substring(0,10) + resultObj.getString("id");
		milianOrderQueryBean.setORDER_ID(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
		milianOrderQueryBean.setUSER_TYPE("02");
		milianOrderQueryBean.setSIGN_TYPE("03");
		milianOrderQueryBean.setORG_ORDER_ID(miLianOrgOrderId);
		milianOrderQueryBean.setUSER_ID(miLianQuickRegister.getMerchantNo());
		String params = ParamsUtil.getQueryOrderParams(milianOrderQueryBean ,miLianQuickRegister);
		String respResult = HttpHelper.doHttp(MLOrderQueryURL, HttpHelper.POST, "UTF-8", params, "60000");
		RequestMsg RM = new RequestMsg();
		XmlUtil xmlUtil = new XmlUtil();
		xmlUtil.XmlToBean(RM, respResult);
		if (RM.getRESP_CODE().equals("0000")) {
			log.info("米联交易成功");
			maps.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			maps.put("channel_type", "milian_quick");
			maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
		}else if(RM.getRESP_CODE().equals("0100")){
			log.info("米联交易处理中");
			maps.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			maps.put("channel_type", "milian_quick");
			maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
		}else{
			log.info("米联交易失败");
			maps.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			maps.put("channel_type", "milian_quick");
			maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
		}
		return maps;
	}

	// 支付接口异步回调接口
	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/milianQuick/paynotify_call")
	public void miLianQuickPayNotifyCallback(HttpServletRequest request, HttpServletResponse response
	) throws Exception {



	}

	/*绑卡查询*/
	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/milianQuick/bindBankCardQuery")
	public @ResponseBody Object mlCardInfoQuery(HttpServletRequest request,
												@RequestParam(value = "userid") String userid,
												@RequestParam(value = "bankCard") String bankCard) throws Exception {
        log.info("米联绑卡查询请求开始");
		MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userid),bankCard);
        Map<String, String> maps = new HashMap<String, String>();
        String params = ParamsUtil.getCardInfoQueryParams(miLianQuickRegister);
        log.info("请求参数：{}",params);
        String respResult = HttpHelper.doHttp(MLCardInfoQueryURL, HttpHelper.POST, "UTF-8", params, "60000");
        log.info("米联绑卡查询请求返回,respResult={}",respResult);
        RequestMsg RM = new RequestMsg();
        XmlUtil xmlUtil = new XmlUtil();
        xmlUtil.XmlToBean(RM, respResult);
        if (RM.getRESP_CODE().equals("0000")) {
            log.info("米联绑卡成功");
            /*更新进件表中状态*/
			topupPayChannelBusiness.updateMiLianRegisterStateByUIdAndBankId(Long.valueOf(userid),bankCard);
            log.info("米联绑卡成功,进件表状态修改成功");
            topupPayChannelBusiness.updateMiLianBindCardStateByIdAndBankId(userid,bankCard);
            log.info("米联绑卡成功,绑卡表状态修改成功");
			maps.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			maps.put("channel_type", "milian_quick");
			maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
        }else{
            log.info("米联绑卡失败");
            maps.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            maps.put("channel_type", "milian_quick");
            maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
        }
        return maps;
    }

    /*绑卡接口*/
	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/milianQuick/bankCard")
	public String miLianBankCard(HttpServletRequest request, @RequestParam(value = "bankNo") String bankNo, Model model
	) throws Exception {
		log.info("米联绑卡接口请求开始");
		MilianBankCardBean milianBankCardBean = new MilianBankCardBean();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/bank/default/cardno";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankNo);
		requestEntity.add("type", "0");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject jsonObject;
		JSONObject resultObj;
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			model.addAttribute("resp_code", CommonConstants.FALIED);
			model.addAttribute("channel_type", "milian_quick");
			model.addAttribute("resp_message", "查询银行卡信息有误");

			/*跳转地址*/
			return "milianquickpayredirect";
		}
		String mobile = resultObj.getString("phone"); // 预留信用卡手机号码
		String idcard = resultObj.getString("idcard");// 身份证号
		String userName = resultObj.getString("userName");// 用户姓名
		String userId = resultObj.getString("userId");// userId
		String cvn2 = resultObj.getString("securityCode");// cvn2
		String valid = resultObj.getString("expiredTime");// valid


		MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userId));

		milianBankCardBean.setOrder_id(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
		milianBankCardBean.setUser_type("02");
		milianBankCardBean.setUser_id(miLianQuickRegister.getMerchantNo());
		milianBankCardBean.setSign_type("03");
		milianBankCardBean.setBus_code("1011");
		milianBankCardBean.setCheck_type("01");
		milianBankCardBean.setAcct_no(bankNo);
		milianBankCardBean.setPhone_no(mobile);
		milianBankCardBean.setId_no(idcard);
		milianBankCardBean.setName(userName);
		milianBankCardBean.setCvn2(cvn2);
		milianBankCardBean.setValid(valid);
		/*页面通知地址*/
		milianBankCardBean.setPage_url("");

		String params = ParamsUtil.getBindCardParams(milianBankCardBean,miLianQuickRegister);
		String respResult = HttpHelper.doHttp(MLBankCardURL, HttpHelper.POST, "UTF-8", params, "60000");
		RequestMsg RM = new RequestMsg();
		XmlUtil xmlUtil = new XmlUtil();
		xmlUtil.XmlToBean(RM, respResult);
		if (RM.getRESP_CODE().equals("0000")) {
			SignUtil signUtil = new SignUtil();
			Boolean checkResult = signUtil.checkSIGN(RM,miLianQuickRegister);
			if (checkResult) {
				/*银联HTML5*/
				String payInfo = RM.getPAY_INFO();
				payInfo = payInfo.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
				String returnHtml = URLDecoder.decode(payInfo, "UTF-8");
				model.addAttribute("resp_code", CommonConstants.SUCCESS);
				model.addAttribute("channel_type", "milian_quick");
				model.addAttribute("resp_message", RM.getRESP_DESCR());
				model.addAttribute("returnHtml", returnHtml);

			} else {
				log.info("请求绑卡接口失败===================" + RM);
				model.addAttribute("resp_code", CommonConstants.FALIED);
				model.addAttribute("channel_type", "milian_quick");
				model.addAttribute("resp_message", RM.getRESP_DESCR());
			}
		}
		else{
			log.info("请求绑卡接口失败===================" + RM);
			model.addAttribute("resp_code", CommonConstants.FALIED);
			model.addAttribute("channel_type", "milian_quick");
			model.addAttribute("resp_message", RM.getRESP_DESCR());
		}
		/*跳转地址*/
		return "milianquickpayredirect";
	}

	/*商户余额查询*/
	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/milianQuick/merchBalanceQuery")
	public @ResponseBody Object miLianMerchBalanceQuery(HttpServletRequest request,
														@RequestParam(value = "userid") String userid,
														@RequestParam(value = "bankCard") String bankCard) throws Exception {
		log.info("开始进入米联商户余额查询接口========================");
		Map<String, String> maps = new HashMap<String, String>();
		MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userid),bankCard);
		String params = ParamsUtil.getMerchBalanceQueryParams(miLianQuickRegister);
		String respResult = HttpHelper.doHttp(MLMerchBalanceQueryURL, HttpHelper.POST, "UTF-8", params, "60000");
		RequestMsg RM = new RequestMsg();
		XmlUtil xmlUtil = new XmlUtil();
		xmlUtil.XmlToBean(RM, respResult);
		if (RM.getRESP_CODE().equals("0000")) {
			log.info("米联商户余额查询成功");
			maps.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			maps.put("channel_type", "milian_quick");
			maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
			maps.put(CommonConstants.RESULT, RM.getBALANCE());
		}else{
			log.info("米联商户余额查询失败");
			maps.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			maps.put("channel_type", "milian_quick");
			maps.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
		}
		return maps;
	}

	/*米联quick 绑定银行卡页面地址*/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/bindcard/ml/return_call")
	public String miLianReturnCallback(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

		log.info("--- start milian_quick_return_call -- ");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String useridbankcard = request.getParameter("useridbankcard");
		log.info("milian_quick_return_call 米联前台页面通知=====结果, useridbankcard:{}",useridbankcard);

		// 主动查询绑卡结果 
		if (!"".equals(useridbankcard) && useridbankcard != null) {
			int splitIndex = useridbankcard.indexOf("__"); 
			String userid = useridbankcard.substring(0,splitIndex);
			String bankCard = useridbankcard.substring(splitIndex+2,useridbankcard.length());
			
			RestTemplate restTemplate = new RestTemplate();
			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
			String url = uri.toString() + "/v1.0/paymentchannel/topup/milianQuick/bindBankCardQuery";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("userid", userid);
			requestEntity.add("bankCard", bankCard);
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			
			log.info("接口/v1.0/paymentchannel/topup/milianQuick/bindBankCardQuery--RESULT================" + result);
			JSONObject jsonObject =  JSONObject.fromObject(result);
			if ("0000".equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
				log.info("米联绑卡成功");
				model.addAttribute("bind_result", "success");
			} else {
				log.info("米联绑卡失败");
				model.addAttribute("bind_result", "error");
			}
			model.addAttribute("resp_desc", jsonObject.getString(CommonConstants.RESP_MESSAGE));
			/*log.info("米联绑卡成功");
			model.addAttribute("bind_result", "success");
			model.addAttribute("resp_desc", "");*/
		} else {
			log.info("米联绑卡失败");
			model.addAttribute("bind_result", "error");
			model.addAttribute("resp_desc", "绑卡异常");
		}
		
		return "milianquickbankReturnPage";
	}


	/*随机获取category经营项目*/
	public static String getCategory(){
		String categoryString = "{\"4900\":\"公共事业\",\"5831\":\"饮酒场所\",\"5812\":\"就餐场所和餐馆\",\"7997\":\"会员俱乐部\",\"7298\":\"健美及美容SPA\",\"7032\":\"运动和娱乐露营地\",\"5094\":\"贵重珠宝，首饰，钟表零售\",\"1520\":\"一般承包商\",\"5933\":\"典当，拍卖，信托\",\"5511\":\"汽车经销商\",\"5499\":\"零食店\",\"5422\":\"自助加油站\",\"5411\":\"大型超市\",\"4121\":\"出租车服务\",\"4131\":\"公路客运\",\"4511\":\"航空公司\",\"5065\":\"电器零件和设备\"}";

		Map<String ,String > map = com.alibaba.fastjson.JSONObject.parseObject(categoryString,Map.class);
		Object[] categorys = map.keySet().toArray();
		int index = (int) (Math.random() * categorys.length);
		return categorys[index].toString();
	}

}